package com.java.blog.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import lombok.extern.log4j.Log4j;

@Log4j
public class RequestTimeInterceptor implements HandlerInterceptor {

	private NamedThreadLocal<Long> requestTimeThreadLocal = new NamedThreadLocal<>("请求时间拦截器");

	// 该方法的返回值是布尔值Boolean 类型的，当它返回为false 时，表示请求结束
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		requestTimeThreadLocal.set(System.currentTimeMillis());
		return true;
	}

	// 该方法将在Controller执行之后，返回视图之前执行
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		long endTime = System.currentTimeMillis();
		long beginTime = requestTimeThreadLocal.get();
		long requestTime = endTime - beginTime;
		log.debug(request.getRequestURI() + "请求时间:" + requestTime);
	}

	// 该方法将在整个请求完成之后，也就是说在视图渲染之后进行调用，主要用于进行一些资源的释放
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("after");

	}
}
